import zipfile
import defs
import config
import StringIO
import csv

class Tile:
	def __init__(self, x, y, t):
		self.x = x
		self.y = y
		self.type = t

tilesize = config.parser.getint("main", "tilesize")

class Map:
	def __init__(self, filename):
		try:
			self.file = zipfile.ZipFile(filename, "r")
		except:
			raise IOError, "Couldn't load map file"
		try:
			mapinfo_string = self.file.read("map.cfg")
		except:
			raise IOError, "Couldn't read map.cfg"
		self.data_parser = config.RRcfgparser()
		self.data_parser.readfp(StringIO.StringIO(mapinfo_string))
		self.name = self.data_parser.get("map", "name")
		self.description = self.data_parser.get("map", "desc")
	def generate_tile_array(self):
		layers = self.data_parser.getlist("map", "layers")
		self.width = self.data_parser.getint("map", "width")
		self.height = self.data_parser.getint("map", "height")
		tiles = []
		for layer in layers:
			current = self.file.open("layers/wall-%s.map" % layer, "r")
			reader = csv.reader(current, delimiter=",")
			for rownum, row in enumerate(reader):
				tiles.append([])
				for tilenum, tile in enumerate(row):
					tiles[-1].append(Tile(rownum*tilesize, tilenum*tilesize, tile))
		return tiles
